import React, { useEffect, useState } from 'react';
import { message, Space, Tag } from 'antd';
import { connect, Dispatch } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import ProCard from '@ant-design/pro-card';
import { CQ_LIST_INIT, CQ_LIST, CQ_DETAIL, CQ_LIST_UNMOUNT } from '@/actions/cq';
import { AGrid, AButton } from '@/components/SelfComp';
import { ConnectState } from '@/models/connect';
import { CqItem, CqDetailItem, CqListQueryParam } from '@/types/cq';
import { DataItem } from '@/types/global';
import { getItemValue } from '@/utils/commons';
import CqListQueryForm from './components/CqListQueryForm';
import ViewCqDrawer from './components/ViewCqDrawer';

interface CqListProps {
  dispatch: Dispatch;
  cqList: CqItem[],
  total: number,
  loading: boolean;
  detailLoading: boolean;
  exportLoading: boolean;
  auditorData: DataItem[],
  designerData: DataItem[],
  systemData: DataItem[];
  cqStatusData: DataItem[];
}

const EMPTY: CqItem = {
  cqId: '',
  cqCode: '',
  cqName: '',
  systemCode: '',
  clstCode: '',
  appCode: '',
  auditor: '',
  designerA: '',
  status: '',
  prdDate: '',
  devStartDate: '',
  devEndDate: '',
  sitStartDate: '',
  sitEndDate: '',
  uatStartDate: '',
  uatEndDate: '',
}

const EMPTY_DETAIL: CqDetailItem = {
  ...EMPTY,
  tradeList: [],
}

/**
 * 需求列表，表格展示需求基本信息，可查看需求详细信息
 */
const CqList: React.FC<CqListProps> = (props) => {
  // 需求详情弹窗
  const [viewDrawerVisible, setViewDrawerVisible] = useState<boolean>(false);
  const [cqDetailFormData, setCqDetailFormData] = useState<CqDetailItem>(EMPTY_DETAIL);
  const [selectedRows, setSelectedRows] = useState<CqItem[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [queryParam, setQueryParam] = useState<CqListQueryParam>();
  // 默认为10
  const [pageSize, setPageSize] = useState<number>(10);
  // const [flag, setFlag] = useState<FlagEnum>('view');

  useEffect(() => {
    console.info('CqList.useEffect');
    // 查询本页面需所有参数
    // 获取所属系统
    // 获取审核人列表
    const { dispatch } = props;
    dispatch(CQ_LIST_INIT({}));
    return () => {
      dispatch(CQ_LIST_UNMOUNT({}));
    }
  }, []);

  const columns = [
    {
      title: '需求编号',
      dataIndex: 'cqCode',
      width: 150
    },
    {
      title: '需求名称',
      dataIndex: 'cqName',
      width: 300,
      ellipsis: true
    },
    {
      title: '所属系统',
      dataIndex: 'systemCode',
      width: 120
    },
    {
      title: '所属集群',
      dataIndex: 'clstCode',
      width: 120
    },
    {
      title: '所属应用',
      dataIndex: 'appCode',
      width: 120
    },
    {
      title: '审核人(主开)',
      dataIndex: 'auditor',
      width: 100
    },
    {
      title: '设计人A',
      dataIndex: 'designerA',
      width: 100
    },
    {
      title: '需求状态',
      dataIndex: 'status',
      width: 150,
      render: (_text: string, record: CqItem, _index: number) => cqStatusFunc(record)
    },
    {
      title: '投产时间',
      dataIndex: 'prdDate',
      width: 100,
    },
    {
      title: 'DEV开始时间',
      dataIndex: 'devStartDate',
      width: 120,
    },
    {
      title: 'DEV结束时间',
      dataIndex: 'devEndDate',
      width: 120,
    },
    {
      title: 'SIT开始时间',
      dataIndex: 'sitStartDate',
      width: 120,
    },
    {
      title: 'SIT结束时间',
      dataIndex: 'sitEndDate',
      width: 120,
    },
    {
      title: 'UAT开始时间',
      dataIndex: 'uatStartDate',
      width: 120,
    },
    {
      title: 'UAT结束时间',
      dataIndex: 'uatEndDate',
      width: 120,
    },
  ];

  /**
   * 需求状态转换
   */
  const cqStatusFunc = (record: CqItem) => {
    const { cqStatusData } = props;
    const { status } = record;
    const value = getItemValue(cqStatusData, status);
    if (status !== '4') {
      return <Tag color='error'>{value}</Tag>;
    }
    return <Tag color='processing'>{value}</Tag>
  }

  /**
   * 分页查询需求信息
   * @param {*} pageNum 页码
   * @param {*} pageSize 每页记录条数
   */
  const fetchAllCq = (pageNum: number, pageSize: number, queryParam?: CqListQueryParam) => {
    const { dispatch } = props;
    dispatch(CQ_LIST({
      ...queryParam,
      pageSize,
      pageNum
    }));
  }

  /**
   * 表单提交
   */
  const handleSubmitEx = (record: CqListQueryParam) => {
    // console.info('TaskList.handleSubmitEx');
    // console.info(record);
    const queryParam = {
      ...record
    };
    // console.info(record);
    // 查询条件保存起来，方便点击页码时使用
    // setState回调方法，保证先更新state
    setQueryParam(queryParam);
    fetchAllCq(1, pageSize, queryParam);
  }

  /**
   * 根据查询条件导出表格数据
   * @param {*} record 查询表单
   */
  const handleExportEx = () => {
    // 先判断表格是否有数据
    const { cqList } = props;
    const size = cqList.length;
    if (size === 0) {
      message.warn('请先查询数据，在导出！');
      return;
    }
    const { total } = props;
    if (total === 5000) {
      message.warning('导出数据总条数超过5000，请增加查询条件！');
      return;
    }
    // 下载文件
    message.success('导出成功');
  }

  const openViewCqDrawer = async () => {
    // 表格选中内容
    console.info('openViewCqDrawer');
    if (selectedRowKeys.length === 0) {
      message.warn('请先选择一条数据!');
      return;
    }
    if (selectedRowKeys.length > 1) {
      message.warn('只能选择一条数据!');
      return;
    }
    const { cqId, status } = selectedRows[0];
    const { dispatch } = props;
    const res = await dispatch(CQ_DETAIL({
      cqId,
      status
    }));
    // console.info(res);
    if (res) {
      const { result } = res;
      // console.info(result);
      const cqFormData = {
        ...result
      }
      setCqDetailFormData(cqFormData);
      setViewDrawerVisible(true);
    }
  }

  const closeViewDrawer = () => {
    setViewDrawerVisible(false);
  }

  const renderLeftButton = () => {
    const { exportLoading, detailLoading } = props;
    return (
      <>
        <AButton type='primary' code='view' pageCode='cq-list' name='查看详细' onClick={openViewCqDrawer} loading={detailLoading} />
        <AButton type='primary' code='export' pageCode='cq-list' name='导出' onClick={handleExportEx} loading={exportLoading} />
      </>
    );
  }

  /**
   * 表格勾选回调函数
   * @param {*} rows 表格选中数据集合
   */
  const onSelectRow = (keys: React.Key[], rows: CqItem[]) => {
    setSelectedRowKeys(keys);
    setSelectedRows(rows);
  };

  /**
   * 页码改变的回调，参数是改变后的页码及每页条数
   * @param page 改变后的页码，上送服务器端
   * @param pageSize 每页数据条数
   */
  const onPageNumAndSizeChange = (page: number, pageSize: number) => {
    console.log(page, pageSize);
    // 页码需要保存起来
    setPageSize(pageSize);
    fetchAllCq(page, pageSize, queryParam);
  };

  const code = 'cq-list';
  const { cqList, loading, total, auditorData, designerData, systemData, cqStatusData } = props;
  const rowKey = (record: CqItem) => record.cqId;
  const pkField = 'cqId';

  return (
    <PageContainer>
      <Space direction='vertical' size='middle' style={{ display: 'flex' }}>
        <ProCard title='查询条件' headerBordered >
          <CqListQueryForm
            colon={false}
            loading={loading}
            auditorData={auditorData}
            designerData={designerData}
            systemData={systemData}
            cqStatusData={cqStatusData}
            onSubmit={handleSubmitEx}
          />
        </ProCard>
        <ProCard>
          <AGrid
            code={code}
            noActionColumn={true}
            renderLeftButton={renderLeftButton}
            columns={columns}
            rowKey={rowKey}
            pkField={pkField}
            dataSource={cqList}
            loading={loading}
            total={total}
            scroll={{x:2300}}
            onSelectRow={onSelectRow}
            onPageNumAndSizeChange={onPageNumAndSizeChange}
          />
        </ProCard>
      </Space>
      {
        !viewDrawerVisible ? null :
        <ViewCqDrawer
          drawerVisible={viewDrawerVisible}
          drawerTitle='需求详细信息'
          drawerWidth={1000}
          colon={false}
          loading={false}
          formData={cqDetailFormData}
          cqStatusData={cqStatusData}
          onHandlerCancel={closeViewDrawer}
        />
      }
    </PageContainer>
  );
}

export default connect((state: ConnectState) => ({
  cqList: state.cqs.rows,
  total: state.cqs.total,
  pageSize: state.cqs.pageSize,
  auditorData: state.users.auditorData,
  designerData: state.users.designerData,
  systemData: state.systems.systemData,
  cqStatusData: state.systems.cqStatusData,
  // 当用户 dispatch 对应 effect 时，dva 会自动注入对应 effect 的 loading 状态
  loading: state.loading.effects['cqs/fetchAllCq'],
  detailLoading: state.loading.effects['cqs/fetchCqDetail'],
  exportLoading: state.loading.effects['cqs/exportCqList'],
}))(CqList);